import {
	post
} from "@/common/js/http.js";
let that = null;
let app = getApp();
export default {
	data() {
		return {
			keyword: '',
			isLoad: false,
			page: 1,
			selectModel: [{
				'name': '课程',
			}, {
				'name': '题目',
			}],
			selectModelIndex: 0,
			page: 1,
			isFinish: false,
			dataList: [],
			pageHeight: 0
		};
	},
	onLoad(options) {
		that = this;
		const {
			keyword = ''
		} = options || {};
		const {
			selectModelIndex = 0
		} = options || {};

		that.keyword = keyword;
		that.selectModelIndex = selectModelIndex;
		that.searchData();
		app.globalData.showShareMenu();
	},
	onShow(options) {},
	onReady() {
		that.pageHeight = app.globalData.screenHeight - 100;
	},
	onShareAppMessage() {
		return app.globalData.getShareConfig();
	},
	methods: {
		selectModelTap(options) {
			let index = options.currentTarget.dataset.id;
			if (index > 1) {
				app.showToast('暂未开放此类目');
				return;
			}
			that.page = 1;
			that.dataList = [];
			that.isFinish = false;
			that.selectModelIndex = index;
			that.searchData();
		},
		onInputChange(options) {
			that.keyword = options.detail.value;
		},
		onSearchClick(options) {
			if (that.keyword.length == 0) {
				app.showToast('请输入关键字');
				return;
			}
			if (that.keyword.length <= 1) {
				app.showToast('关键词长度太短啦');
				return;
			}
			that.page = 1;
			that.dataList = [];
			that.isFinish = false;
			that.searchData();
		},
		searchData() {
			if (that.keyword == '') {
				return;
			}
			if (that.selectModelIndex == 0) {
				that.searchCourse();
			}
			if (that.selectModelIndex == 1) {
				that.searchQuestion();
			}
		},
		async searchCourse() {
			let apiUrl = 'course/search';
			let res = await post(apiUrl, {
				page: that.page,
				keyword: that.keyword
			})
			that.dataList = that.dataList.concat(res.data);
			if (res.data.length == 0) {
				that.isFinish = true;
			} else {
				that.page++;
			}
			that.isLoad = true;
			console.log(res);
		},
		async searchQuestion() {
			let apiUrl = 'question/new_search';
			let res = await post(apiUrl, {
				page: that.page,
				keyword: that.keyword
			})
			that.dataList = that.dataList.concat(res.data);
			if (res.data.length == 0) {
				that.isFinish = true;
			} else {
				that.page++;
			}
			that.isLoad = true;
			console.log(res);
		},
		onClickItem(options) {
			console.log(options);
			let id = options.currentTarget.dataset.id;
			let url = that.selectModelIndex == 0 ? '../practice/course/detail?id=' : '../practice/question/detail?id=';
			uni.navigateTo({
				url: url + id
			});
		},
		loadMore() {
			console.log(1);
			if (!that.isFinish) {
				that.searchData();
			}
		}
	}
};